<template>
  <div class="thumbnails-view" style="position:absolute;z-index:10;left:100vw;">
    <div class="thumbnails" ref="generatorRef">
      <ThumbnailSlide class="thumbnail" v-for="slide in renderSlides" :key="slide.id" :slide="slide" :size="1600" />
    </div>
  </div>
  <div class="editor-header" style="margin-top: 3px;">
    <div class="left">
      <!-- <Tooltip :mouseLeaveDelay="0" title="导出">
        <div class="menu-item" @click="setDialogForExport('pptist')">
          <IconShare size="18" fill="#666" />
        </div>
      </Tooltip> -->
      <Tooltip :mouseLeaveDelay="0" title="幻灯片放映">
        <div class="menu-item" @click="enterScreening()">
          <IconPpt size="19" fill="#666" style="margin-top: 1px;" />
        </div>
      </Tooltip>
    </div>

    <div class="right">
      <!-- <span class="span-tip">页面会自动保存</span> -->
      <!-- <IconRightTwo theme="filled" size="24" fill="#f00" /> -->
      <div>
        <Button @click="preserve()" style="margin-left: 12px;" v-if="type === 'student'">
          保存
        </Button>
        <!-- <RationalismSubmitButton v-if="user_type==='student'" /> -->
      </div>
    </div>

    <Drawer width="320" placement="right" :closable="false" :visible="hotkeyDrawerVisible"
      @close="hotkeyDrawerVisible = false">
      <HotkeyDoc />
    </Drawer>

    <FullscreenSpin :loading="exporting" tip="正在提交..." />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useAskStore, useMainStore, useSlidesStore } from '@/store'
import useScreening from '@/hooks/useScreening'
import HotkeyDoc from './HotkeyDoc.vue'
import FullscreenSpin from '@/components/FullscreenSpin.vue'
import { Button, Tooltip, Menu, Drawer, message } from 'ant-design-vue'
import http from '@/utils/http'
import useExport from '@/hooks/useExport'
import ThumbnailSlide from '@/views/components/ThumbnailSlide/index.vue'
import { toPng, toJpeg } from 'html-to-image'
interface ExportImageConfig {
  quality: number
  width: number
  fontEmbedCSS?: string
}

const mainStore = useMainStore()
const askStore = useAskStore()
const { preserve_pdf_url, group_id, record_id, sub_key, type } = storeToRefs(askStore)

const { enterScreening } = useScreening()

const { slides } = storeToRefs(useSlidesStore())

const setDialogForExport = mainStore.setDialogForExport

const hotkeyDrawerVisible = ref(false)
const exporting = ref(false)
const generatorRef = ref<HTMLElement>()
const rangeType = ref('full')

// let renderSlides = computed(() => rangeType.value === 'full' ? slides.value : [slides.value[0]])
const renderSlides = computed(() => {
  if ( rangeType.value.includes('decision')) {
    const index = Number(rangeType.value.split('decision')[1])
    return [slides.value[index]]
  } 
  return rangeType.value === 'full' ? slides.value : [slides.value[0]]
})

const { exportImage } = useExport()

const channel = new BroadcastChannel('savePPT')

const getImage = async (): Promise<string> => {
  if (!generatorRef.value) return ''
  const foreignObjectSpans = generatorRef.value.querySelectorAll('foreignObject [xmlns]')
  foreignObjectSpans.forEach(spanRef => spanRef.removeAttribute('xmlns'))

  return await new Promise(reslove => {
    setTimeout(() => {
      if (!generatorRef.value) return
      toJpeg(generatorRef.value)
        .then(dataUrl => reslove(dataUrl))
        .catch(() => {
          exporting.value = false
          // message.error('导出图片失败')
          reslove('')
        })
    }, 500)
  })
}

const getDecisionImage = async ( ) => {
  const decision_image = []
  for ( let i = 1; i < slides.value.length - 1; i++) {
    rangeType.value = `decision${i}`
    const target = await getImage()
    decision_image.push(target)
  }
  return decision_image
}

const preserve = async (): Promise<void> => {
  // 获取完整数据
  rangeType.value = 'full'
  const full_image = await getImage()
  // 获取封面数据
  rangeType.value = 'cover'
  const cover_image = await getImage()
  // 获取决策图片列表
  const decision_image = await getDecisionImage()
  http.post(preserve_pdf_url.value, {
    funcName: 'SavePptInfo',
    options: {
      cover_image, full_image, decision_image, type: type.value, record_id: record_id.value,
      group_id: group_id.value, sub_key: sub_key.value, ppt_content: JSON.stringify(slides.value)
    }
  }).then(() => {
    channel.postMessage({key: sub_key.value, status: !!full_image && !!cover_image ? 'success' : 'error'})
  }).catch(() => {
    channel.postMessage({key: sub_key.value, status: 'error'})
  })
}

channel.onmessage = ({data: {key}}) => {
  key === sub_key.value && preserve()
}

window.parent['getPPtContent'] = () => {
  return JSON.stringify(slides.value)
}
</script>

<style lang="scss" scoped>
.editor-header {
  background-color: #fff;
  user-select: none;
  border-bottom: 1px solid $borderColor;
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}

.left,
.right {
  display: flex;
  justify-content: center;
  align-items: center;
}

.menu-item {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  padding: 0 10px;
  cursor: pointer;

  .text {
    margin-left: 4px;
  }
}

.right .span-tip {
  font-size: 16px;
  color: #aaa;
}

.left .menu-item:hover {
  background-color: #f9f9f9;
}

.editor-top {
  padding: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>